package com.maple.object;

import java.lang.reflect.Field;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

public class BeanUtilsw {
	public static void overrideToString(Object obj)
	{
		if(obj==null)
		{
			System.out.println("this instance is null.");
			return ;
		}
		Class c=obj.getClass();
		Field[] fields=c.getDeclaredFields();
		System.out.println("in this "+c.getName()+" object:");
		try {
			for (Field field : fields) {
				field.setAccessible(true);
				System.out.print(field.getName() +": "+field.get(obj)+",");
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		} 
	}
	
	public static <T> void showList(List<T> list)
	{
		for (int i = 0; i < list.size(); i++) {
			BeanUtilsw.overrideToString(list.get(i));
		}
	}
	/**
	 * @param defaultValue 如果没法正确返回属性值,就返回defaultValue
	 * @param bean
	 * @param name
	 * @return
	 */
	public  static String getProperty(Object bean,String name,String defaultValue)
	{
		if(bean==null)
			return defaultValue;
		String s=null;
		try{
			s=BeanUtils.getProperty(bean, name);
			if(s==null)
				return defaultValue;
		}catch(Exception e)
		{
			return defaultValue;
		}
		return s;
	}
	/**
	 * @param defaultValue 如果没法正确返回属性值,就返回defaultValue
	 * @param bean
	 * @param name
	 * @return
	 */
	public  static  boolean getProperty(Object bean,String name,boolean defaultValue)
	{
		if(bean==null)
			return defaultValue;
		String s=null;
		try{
			s=BeanUtils.getProperty(bean, name);
			if(s==null)
				return defaultValue;
		}catch(Exception e)
		{
			return defaultValue;
		}
		return !defaultValue;
	}
	/**
	 * @param bean
	 * @param name
	 * @return
	 */
	public  static String getProperty(Object bean,String name)
	{
		if(bean==null)
			return "";
		String s="";
		try{
			s=BeanUtils.getProperty(bean, name);
			if(s==null)
				return "";
		}catch(Exception e)
		{
			return "";
		}
		return s;
	}
}
